<?php

/*
user_model:负责用户控制功能，包括：
用户登录检查
用户权限检查
管理用户，增、删、查、改
*/

class Main_goods_model extends CI_Model
{

	private $table = 'main_goods';
	public $data = '';

	function __construct()
	{
		parent::__construct();
		//载入库文件
		$this->load->library('test_database');
		$this->test_database->test();
		//载入核心类
		$this->load->database($this->test_database->get_db());
		//载入库文件
		$this->load->library('form_validation');
		$this->load->library('session');
		//载入辅助类
		//$this->load->helper('cookie');
		//载入本地语言文件
		$this->lang->load('form_validation','chinese');
	}

	public function create()
	{
		$this->form_validation->set_rules('type_id', '类目', 'trim|required|xss_clean|existType[Goods_type_model]');
		$this->form_validation->set_rules('number', '货号', 'trim|required|min_length[6]|max_length[20]|alpha_numeric|unique[Main_goods_model]|unique[Main_goods_model,number]|xss_clean');
		$this->form_validation->set_rules('name', '名称', 'trim|required|min_length[6]|max_length[30]|xss_clean');
		$this->form_validation->set_rules('search_code', '搜索代码', 'trim|required|min_length[1]|max_length[30]|alpha_dash|unique[Main_goods_model,search_code]|xss_clean');
		$v['taobao_link'] = $this->input->post('taobao_link');
		if (!empty($v['taobao_link']))
		{
			$this->form_validation->set_rules('taobao_info', '链接', 'trim|min_length[20]|max_length[100]|is_url|xss_clean');
		}
		if ($this->form_validation->run())
		{
			$v['goods_type_id'] = $this->input->post('type_id');
			$v['number'] = $this->input->post('number');
			$v['name'] = $this->input->post('name');
			$v['search_code'] = $this->input->post('search_code');
			$v['create_date'] = time();
			$v['update_date'] = $v['create_date'];
			$v['taobao_info'] = '{"url":"","image":"","name":""}';
			if (!empty($v['taobao_link']))
			{
				$v['taobao_info'] = '{"url":"' . $this->input->post('taobao_link') . '", "image":"","name":""}';
			}
			unset($v['taobao_link']);
			$query = $this->db->insert($this->table, $v);
			if ($this->db->insert_id())
			{
				return true;
			}
		}
		return false;
	}

	public function update()
	{
		$this->form_validation->set_rules('type_id', '类目', 'trim|required|xss_clean|existType[Goods_type_model]');
		//$this->form_validation->set_rules('number', '货号', 'trim|required|min_length[6]|max_length[20]|alpha_numeric|unique[Main_goods_model]|xss_clean');
		$this->form_validation->set_rules('name', '名称', 'trim|required|min_length[6]|max_length[30]|xss_clean');
		$this->form_validation->set_rules('search_code', '搜索代码', 'trim|required|min_length[1]|max_length[30]|alpha_dash|unique[Main_goods_model,search_code,false]|xss_clean');
		$v['taobao_url'] = $this->input->post('taobao_url');
		if (!empty($v['taobao_url']))
		{
			$this->form_validation->set_rules('taobao_url', '链接', 'trim|min_length[20]|max_length[100]|is_url|xss_clean');
		}
		if ($this->form_validation->run())
		{
			$v['goods_type_id'] = $this->input->post('type_id');
			//$v['number'] = $this->input->post('number');
			$v['name'] = $this->input->post('name');
			$v['search_code'] = $this->input->post('search_code');
			$v['update_date'] = time();
			//处理淘宝信息
			$v['taobao_info'] = '{"url":"","image":"","name":""}';
			if (!empty($v['taobao_url']))
			{
				$this->db->where('main_goods_id', $this->input->post('main_goods_id'));
				$this->db->like('taobao_info', $this->input->post('taobao_url'));
				$query = $this->db->get($this->table);
				//判断连接是否是同一个链接
				if ($query->num_rows() < 1)
				{
					$v['taobao_info'] = '{"url":"' . $this->input->post('taobao_url') . '", "image":"","name":""}';
				}
				else
				{
					unset($v['taobao_info']);
				}
			}
			unset($v['taobao_url']);
			$this->db->where('main_goods_id', $this->input->post('main_goods_id'));
			$query = $this->db->update($this->table, $v);
			return true;
		}
		return false;
	}

	public function del($main_goods_id)
	{
		if ($this->getOne($main_goods_id))
		{
			$data = array('del_flg' => 1);
			$this->db->where('main_goods_id', $main_goods_id);
			$this->db->update($this->table, $data);
			//return $this->input->post('main_goods_id');
			return true;
		}
		return false;
	}

	public function recover($main_goods_id)
	{
		if ($this->getOne($main_goods_id))
		{
			$data = array('del_flg' => 0);
			$this->db->where('main_goods_id', $main_goods_id);
			$this->db->update($this->table, $data);
			//return $this->input->post('main_goods_id');
			return true;
		}
		return false;
	}

	public function getOne($id)
	{
		$this->db->where('main_goods_id', $id);
		$query = $this->db->get($this->table, 1);
		if ($query->num_rows() > 0)
		{
			foreach ($query->result_array() as $v)
			{
				$v['taobao_info'] = json_decode($v['taobao_info'], TRUE);
				$v['taobao_url'] = $v['taobao_info']['url'];
				$v['taobao_image'] = empty($v['taobao_info']['image'])?'':$v['taobao_info']['image'];
				return $v;
			}
		}
		$this->error = '指定主货物不存在 ID:' . $id;
		return false;
	}

	//getOne($id)方法的别名
	public function get_one($main_goods_id)
	{
		return $this->getOne($main_goods_id);
	}

	public function search($type, $q, $del_flg=FALSE)
	{
		if ($del_flg)
		{
			$del_flg = intval($del_flg);
		}
		if ('n' == $type)
		{
			$this->db->like('number', $q);
		}
		else if ('s' == $type)
		{
			$this->db->like('search_code', $q);
		}
		if (0 === $del_flg || 1 === $del_flg)
		{
			$this->db->where('del_flg', $del_flg);
		}
		$query = $this->db->get($this->table);
		return $query->result();
	}

<<<<<<< HEAD
	//获得所有主货物信息
	public function get_all($select=FALSE, $del_flg=FALSE)
	{
		if ($select)
		{
			$this->db->select($select);
		}
		if ($del_flg)
		{
			$this->db->where('del_flg', $del_flg);
		}

		if ($query = $this->db->get($this->table))
		{
			return $query->result();
		}
		else{
			exit('SYSTEM ERROR! PLEASE CONTACT THE ADMINISTRATOR.');
		}
	}

=======
>>>>>>> ff5f7ef6de592146b376adc8ed0c004b06507151
	public function getList($opt, $start, $limit='')
	{
		if ('enable' == $opt)
		{
			$this->db->where('del_flg', 0);
		}
		else if ('disable' == $opt)
		{
			$this->db->where('del_flg', 1);
		}
		else
		{
			return false;
		}

		if (!empty($limit))
		{
			$this->db->limit($start, $limit);
		}

		$query = $this->db->get('main_goods');
		return $query->result();
	}

	//同步淘宝基本信息
	public function sync_taobao()
	{
		$main_goods_id = $this->input->post('main_goods_id');
		$taobao_url = $this->input->post('taobao_url');
		$taobao_image_root = 'http://img03.taobaocdn.com/bao/uploaded/';
		if ($this->getOne($main_goods_id))
		{
			if ($this->form_validation->is_url($taobao_url))
			{
				//获得淘宝链接DOM源代码
				$content = file_get_contents($taobao_url);
				if ($content)
				{
					//转化编码 GBK 到 UTF8
					$content = mb_convert_encoding($content, 'UTF-8', 'EUC-CN');
					//过滤特征码
					$pattern = '/<div\s*id="J_itemViewed".*?>/';
					if (preg_match($pattern, $content, $matchs))
					{	
						$pattern = '/\{.*\}/';
						$line = $matchs[0];
						if (preg_match($pattern, $matchs[0], $matchs))
						{
							//处理数据准备更新数据库
							$arr = json_decode($matchs[0], true);
							$data = array();
							$data['url'] = $arr['url'];
							$data['image'] = $taobao_image_root . $arr['pic'];
							$data['name'] = $arr['title'];
							//encode json
							$v['taobao_info'] = '{';
							foreach ($data as $key=>$value)
							{
								$v['taobao_info'] .= '"' . $key . '":"' . $value . '",';
							}
							$v['taobao_info'] = substr($v['taobao_info'], 0, -1) . '}';
							$this->db->where('main_goods_id', $main_goods_id);
							$this->db->update($this->table, $v);
							//echo $this->db->last_query();
							$this->data = $data['image'];
							return true;
						}
					}
				}
				$this->error = '请确认链接有效性';
				return false;
			}
			else
			{
				$this->error = '无效的链接';
				return false;
			}
		}
		else
		{
			$this->error = '同步货品不存在';
			return false;
		}
	}

	public function totleRows($opt)
	{
		if ('enable' == $opt)
		{
			$this->db->where('del_flg', 0);
		}
		else if ('disable' == $opt)
		{
			$this->db->where('del_flg', 1);
		}
		$query = $this->db->get('main_goods');
		return $query->num_rows();
	}
	
	public function unique($value, $col=false, $self=false)
	{
		if ($col)
		{
			$this->db->where($col, $value);
			if ($self)
			{
				$this->db->where('main_goods_id !=', $this->input->post('main_goods_id'));
			}
			$query = $this->db->get($this->table);
		}
		else
		{
			$query = $this->db->get_where($this->table, array('main_goods_id' => $value));
		}
		if ($query->num_rows() == 0)
		{
			return true;
		}

		return false;
	}

}